package com.atguigu.tingshu.common.config.redis;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: atguigu
 * @create: 2025-03-19 10:15
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties("spring.data.redis")
public class RedissonConfig {

    @Autowired
    private RedisProperties redisProperties;

    private String host;

    private String password;

    private String port;

    private int timeout = 3000;
    private static String ADDRESS_PREFIX = "redis://";

    /**
     * 是Redisson框架提供所有分布式服务跟分布式对象基础
     */
    @Bean
    RedissonClient redissonSingle() {
        Config config = new Config();

        //修改默认看门狗/释放锁锁时间   默认加锁成功后：锁有效10s  底层看门狗执行定时任务延迟时间:10/3s
        config.setLockWatchdogTimeout(10*1000);
        if (StringUtils.isBlank(host)) {
            throw new RuntimeException("host is  empty");
        }
        SingleServerConfig serverConfig =
                //Redis单节点
                config.useSingleServer()
                //Redis主从集群 配置所有主从节点IP端口
                //config.useMasterSlaveServers()
                //Redis哨兵集群: 配置所有哨兵节点IP端口
                //config.useSentinelServers()
                //Redis分片集群 配置所有主从节点IP跟端口
                //config.useClusterServers()
                .setAddress(ADDRESS_PREFIX + this.host + ":" + port)
                .setTimeout(this.timeout);
        if (StringUtils.isNotBlank(this.password)) {
            serverConfig.setPassword(this.password);
        }
        return Redisson.create(config);
    }
}
